<?php
// 助手函数

// 模板调用
if (!function_exists('view')) {
function view($template=''){
    global $app,$controller,$action;
    $template= $template==''? $controller.'/'.$action.'.php' : $template;
    return _APP_PATH_ . '/' . _ADDONS_NAME_ . '/'.$app.'/view/'.$template;
}
}

// url网址跳转
if (!function_exists('url')) {
function url($url,$vars = ''){
    global $app,$controller,$action;

    $protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ?"https://": "http://";

    if( is_array($url) && isset($url[3]) ){
		$dirname= str_replace('\\','/',dirname($_SERVER['PHP_SELF']) );
		$dirname = $dirname=='/'?'':$dirname;
        $phpself = $dirname . '/' . $url[3] ;
    }else{
        $phpself = $_SERVER['PHP_SELF'];
    }
	
    //$url = '?app='.$url[0].'&c='.$url[1].'&a='.$url[2];
	if( is_array($url) ){
		$url = '?' . $GLOBALS['config']['var_pathinfo'] . '='.$url[0].'/'. str_replace( '/','.',$url[1] ) .'/'.$url[2];	
	}else{
		$url = '?' . $GLOBALS['config']['var_pathinfo'] . '=' . $url ; // '?s=' . $url ;
	}
    if(!empty($vars)){
        // 解析参数
        if (is_array($vars)) {
            // aaa=1&bbb=2 转换成数组
            //parse_str($vars, $vars);
            $vars = http_build_query($vars);
        }
        $vars = '&' . $vars;
    }
    
    return $protocol . $_SERVER['HTTP_HOST'] . $phpself . $url . $vars;
}
}


// 表名函数
if (!function_exists('tablename')) {
    function tablename($name){
        return  ' `' .$GLOBALS['config']['database']['prefix'] . $name . '` ';
    }
}


// 消息跳转（message）
if (!function_exists('message')) {
    function message( $message, $url, $wait= 2 ){
        require _APP_PATH_ . '/framework/tpl/message.tpl.php';
        exit();
    }
}

//获取用户IP地址
function get_ip()
{

    if(!empty($_SERVER["HTTP_CLIENT_IP"]))
    {
        $cip = $_SERVER["HTTP_CLIENT_IP"];
    }
    else if(!empty($_SERVER["HTTP_X_FORWARDED_FOR"]))
    {
        $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    }
    else if(!empty($_SERVER["REMOTE_ADDR"]))
    {
        $cip = $_SERVER["REMOTE_ADDR"];
        if($cip=='::1'){
            $cip = '127.0.0.1';
        }
    }else{
        $cip = '';
    }
    preg_match("/[\d\.]{7,15}/", $cip, $cips);
    $cip = isset($cips[0]) ? $cips[0] : $cip;   //'unknown'
    unset($cips);

    return $cip;
}


// PHPwork上传文件管理器
if (!function_exists('tpl_file_manager')) {
    function tpl_file_manager(  $input=[],$config=[] ){
        $input_name= $input[0];

        if( isset($input[1]) && $input[1]!='' ){
            if( is_array($input[1]) ){
                $input_value= $input[1];    //传一维数组
            }else{
                $input_value[]= $input[1];  // 传字符串
            }
            
        }else{
            $input_value= [];
        }

        //['accept'=>'images','multiple'=>false]
        $config['accept'] = isset($config['accept'])? $config['accept'] :'images';  //允许上传时校验的文件类型，可选值有：images（图片）、file（所有文件）、video（视频）、audio（音频）
        $config['multiple'] = isset($config['multiple'])? $config['multiple'] : false ; // 选择 false单个文件 true多个
        
        $s= '';
        /*
        $s.='<button class="layui-btn" type="button" id="phpwork-tmp_btn_' . $input_name . '" onclick=\'phpwork_file_manage( "'.$input_name.'" , '. json_encode($config) .')\'  ';
        $s.=' title="选择' . ($config['multiple']==true?'多个':'一个') . '文件" >';
        $s.='<i class="layui-icon layui-icon-upload"></i> 选择';
            if($config['accept']=='images') $s.= '图片';
            if($config['accept']=='file')   $s.= '文件';
            if($config['accept']=='video')  $s.= '视频';
            if($config['accept']=='audio')  $s.= '音频';
        $s.='</button>';
        */

        $s.='<div class="phpwork-uploader_list phpwork-tmp_' . $input_name . '">';
        foreach($input_value as $vo){
			//判断图片是否是网络图片
            //if(strpos($vo,'http://') !== false || strpos($vo,'https://') !== false){ 
                $image_url = $vo;	// 原路径图片
            //}else{
                //$image_url = _APP_URL_  . '/' . $vo;
            //}
			
            $s.='<div class="phpwork-item" >';
            $s.='<a href="'. $image_url . '" target="_blank">';
            

            $f_ext = strtolower( pathinfo($vo , PATHINFO_EXTENSION) );
            if( $f_ext === 'jpg' || $f_ext === 'jpeg' || $f_ext === 'png' || $f_ext === 'gif' || $f_ext === 'bmp' ){
                $s.='<img src="' . $image_url . "\" title=\"点击查看大图\n" . $image_url . '" loading="lazy">';
            }else{
                $s.= '<img src="' . _APP_URL_  . '/library/deep/upload/ico/' .  $f_ext . ".png\" title=\"点击查看文件\n" . $image_url . '" loading="lazy">';
            }  

            $s.='</a>';
            $s.='<img src="' . _APP_URL_  . '/library/deep/upload/close.png" title="删除" >';

            if($config['multiple']==true){
                $s.='<input type="hidden" name="' . $input_name . '[]" value="' . $image_url . '">';
            }else{
                $s.='<input type="hidden" name="' . $input_name . '" value="' . $image_url . '">';
            }
            $s.='</div>';
        }
        $s.='<div class="phpwork-btn_upload" type="button" id="phpwork-tmp_btn_' . $input_name . '" onclick=\'phpwork_file_manage( "'.$input_name.'" , '. json_encode($config) .')\'  ';
        $s.=' title="选择' . ($config['multiple']==true?'多个':'一个') ;
            if($config['accept']=='images') $s.= '图片';
            if($config['accept']=='file')   $s.= '文件';
            if($config['accept']=='video')  $s.= '视频';
            if($config['accept']=='audio')  $s.= '音频';
        $s.= '文件'.'" >';
        $s.='<i class="layui-icon layui-icon-addition"></i>';
        $s.='</div>';
        
        $s.='</div>';
        $s.='<script>$(".phpwork-tmp_' . $input_name . '").sortable();</script>';


        return $s;
    }
}

//api接口---token生成
if (!function_exists('token_create')) {
    function token_create($uid,$tablename){
        //查询是否存在该用户
        $sql="select * from ".tablename($tablename)." where uid=".$uid;
        $user=$GLOBALS['db']->query($sql)->fetch();
        if(!empty($user)){
            $token=sha1(md5('deep'.time().mt_rand(10000,99999).$uid));
            $expires_in=time()+7200;
            $data=[
                'token'=>$token,
                'expires_in'=>$expires_in
            ];
            $ok=pdo_update($tablename,$data,['uid'=>$uid]);
            if($ok){
                $arr['code']=1;
                $arr['token']=$token;
                $arr['expires_in']=$expires_in;
            }else{
                $arr['code']=0;
                $arr['token']='';
                $arr['expires_in']='';
            }
        }else{
            $arr['code']=-1;
            $arr['token']='';
            $arr['expires_in']='';  
        }
        return $arr;
    }
}


// 修改用户积分
if (!function_exists('global_wallet_update')) {
    function global_wallet_update($uid,$type='point',$value=0,$module='',$remark=''){
        //插入到系统积分纪录表
        $data=array(
            'uid'=>$uid,
            'type'=>$type,
            'module'=>$module,
            'value'=>$value,
            'remark'=>$remark,
			'create_time'=> date('Y-m-d H:i:s')
        );
        $ok=pdo_insert('sys_wallet_log',$data);
        if($ok){
            //添加成功修改用户表积分
            $sql="select * from ".tablename('sys_member')." where uid='".$uid."' ";
            $member=$GLOBALS['db']->query($sql)->fetch();
            //判断时积分还是余额
            if($type=='point'){
                //修改积分
                pdo_update('sys_member', ['point'=>$member['point']+$value ], ['uid'=>$uid] );
            }else{
                //修改余额
                pdo_update('sys_member', ['money'=>$member['money']+$value ], ['uid'=>$uid] );
            }
        }
        return $ok;
    }
}

